<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/1/22 17:03
 * Remark:
 */

namespace App\Http\Middleware\Department;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\RequestConsts\RequestMethodConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Models\Company\CompanyModel;
use App\Models\Department\DepartmentModel;
use Closure;
use Illuminate\Http\Exceptions\HttpResponseException;

class DepartmentLegitimacyMiddleware
{
    private DepartmentModel $_departmentModel;
    private CompanyModel $_companyModel;

    public function __construct()
    {
        $this->_departmentModel = new DepartmentModel();
        $this->_companyModel = new CompanyModel();
    }


    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $method = strtolower($request->method());
        switch ($method){
            case RequestMethodConsts::GET_METHOD:
                //
                break;
            case RequestMethodConsts::POST_METHOD:
                //新增的时候校验当前公司是否存在
                $this->verifyCompanyIsExists($request->post('company_id'));
                // 新增的时候校验名称是否重复
                $this->verifyCompanyDepartmentNameIsExists($request->post('department_name'), $request->post('company_id'));
                // 新增时候校验他的父部门是否存在
                if($request->post('department_parent_id')){
                    $this->verifyCompanyDepartmentIsExists($request->post('department_parent_id'), $request->post('company_id'));
                }
                break;
            case RequestMethodConsts::PUT_METHOD:
                $departmentId = $request->departmentId;
                // 修改的时候校验部门是否存在
                $this->verifyDepartmentIsExists($departmentId);
                // 如果修改了部门名称 判断当前部门名称是否已经存在
                if($request->post('department_name')){
                    $this->verifyDepartmentNameIsExistsByEdit($departmentId, $request->post('department_name'));
                }
                // 如果修改了父节点 判断当前节点是否有子节点如果有则不能修改
                if($request->post('department_parent_id')) {
                    if($request->post('department_parent_id') == $departmentId){
                        throw new HttpResponseException( ResponseFunc::returnJson(
                            'error',
                            '',
                            "上级部门不能为自己",
                            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                        ));
                    }
                    $this->verifyDepartmentParentIsExists($departmentId,"当前部门存在子部门不能调整架构");
                }
                break;
            case RequestMethodConsts::PATCH_METHOD:
                $departmentId = $request->departmentId;
                // 删除的时候校验部门是否存在
                $this->verifyDepartmentIsExists($departmentId);
                // 删除的时候校验当前节点是否存在子节点
                $this->verifyDepartmentParentIsExists($departmentId,"当前部门存在子部门不能删除");
                break;
            default:
                break;
        }

        return $next($request);
    }


    /**
     * 校验公司名称是否存在
     * @param $companyId
     */
    private function verifyCompanyIsExists($companyId){
        $isExist = $this->_companyModel->isExistByCondition([
            'company_id' => $companyId,
            'status' => BaseConsts::STATUS_NORMAL
        ]);
        if(!$isExist){
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                '公司不存在或已删除',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
    }

    /**
     * 校验部门名称是否存在
     * @param $departmentName
     * @param $companyId
     */
    private function verifyCompanyDepartmentNameIsExists($departmentName, $companyId){
        $isExist = $this->_departmentModel->isExistByCondition([
            'department_name' => $departmentName,
            'company_id' => $companyId,
            'status' => BaseConsts::STATUS_NORMAL
        ]);
        if($isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                '部门名已存在',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
    }

    /**
     * 修改时检验部门名称是否存在
     * @param $departmentId
     * @param $departmentName
     */
    private function verifyDepartmentNameIsExistsByEdit($departmentId, $departmentName){
        $departmentInfo = $this->_departmentModel->getDepartmentInfoByDepartmentIdModel($departmentId);
        $resDepartmentInfo = $this->_departmentModel->getDepartmentInfoModelByDepartmentName($departmentName,["department_id","company_id"]);
        if($resDepartmentInfo && $resDepartmentInfo->department_id != $departmentId && $departmentInfo->company_id == $resDepartmentInfo->company_id){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                '部门名已存在',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
    }

    /**
     * 校验公司下部门是否存在
     * @param $departmentId
     */
    private function verifyCompanyDepartmentIsExists($departmentId, $companyId){
        $isExist = $this->_departmentModel->isExistByCondition([
            'department_id' => $departmentId,
            'company_id' =>$companyId,
            'status' => BaseConsts::STATUS_NORMAL
        ]);
        if(!$isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                "父部门不存在或已删除",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
    }

    /**
     * 校验部门是否存在
     * @param $departmentId
     */
    private function verifyDepartmentIsExists($departmentId){
        $isExist = $this->_departmentModel->isExistByCondition([
            'department_id' => $departmentId,
            'status' => BaseConsts::STATUS_NORMAL
        ]);
        if(!$isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                "当前部门不存在",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
    }

    /**
     * 校验当前部门是否为它部门父级
     * @param $departmentId
     * @param $msg
     */
    private function verifyDepartmentParentIsExists($departmentId,$msg){
        $isExist = $this->_departmentModel->isExistByCondition([
            'department_parent_id' => $departmentId,
        ]);
        if($isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                $msg,
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
    }

    /**
     * 校验当前部门是否为它部门父级
     * @param $departmentId
     * @param $msg
     */
    private function verifyDepartmentHasChildIsExists($departmentId){
        $isExist = $this->_departmentModel->isExistByCondition([
            'department_parent_id' => $departmentId,
        ]);
        if($isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                '当前部门存在子部门不能进行此操作',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,

            ));
        }
    }
}